<template>
  <client-only>
    <el-table-column
      v-if="item.type == 'index'"
      type="index"
      :label="item.label"
      :width="item.width"
    >
    </el-table-column>
    <el-table-column
      v-if="item.type == 'selection'"
      type="selection"
      :prop="item.prop"
      :label="item.label"
      :width="item.width"
    />
    <el-table-column
      v-else-if="item.type == 'expand' && item.children"
      type="expand"
      :prop="item.prop"
      :label="item.label"
      :width="item.width"
    >
      <template #default="props">
        <h3>套餐</h3>
        <div style="padding: 20px">
          <Table :columns="item.children" :data-source="props.row.packages" />
        </div>
      </template>
    </el-table-column>
    <el-table-column
      v-else-if="item.prop"
      :key="item.prop"
      :fixed="item.fixed"
      :prop="item.prop"
      :width="item.width"
      :scrollbar-always-on="true"
      :label="item.label ?? item.prop"
      :show-overflow-tooltip="showOverflowTooltip"
      v-bind="item.componentProps"
      :align="item.componentProps?.align ?? 'left'"
    >
      <template #default="scope">
        <el-config-provider :size="'small'">
          <template
            v-if="item.type === 'action' && Array.isArray(item.buttonGroup)"
          >
            <div style="display: flex">
              <div class="table-column-btns">
                <span
                  v-for="(action, index) in item.buttonGroup.slice(0, 5)"
                  :key="index"
                  style="display: flex; align-items: center"
                >
                  <template v-if="matchActionStatus(action, scope.row)">
                    <el-button
                      v-btnPermission="action.permissions || 'all'"
                      :title="action.permissions"
                      :style="
                        index != 0
                          ? `margin-left: 10px;color:${action.color}`
                          : `color: ${action.color}`
                      "
                      v-bind="action"
                      @click="() => action.click?.(scope.row, scope.$index)"
                    >
                      {{ action.label }}
                    </el-button>
                    <div
                      class="line"
                      v-if="item.buttonGroup.length != index + 1"
                    ></div>
                  </template>
                </span>
              </div>
              <template v-if="item.buttonGroup.slice(5).length > 0">
                <el-dropdown style="margin-left: 10px" placement="bottom-start">
                  <el-button> 更多 </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <div class="table-column-btns">
                        <div
                          v-for="(action, index) in item.buttonGroup.slice(5)"
                          :key="index"
                        >
                          <el-dropdown-item>
                            <template
                              v-if="matchActionStatus(action, scope.row)"
                            >
                              <div
                                @click="
                                  () => action.click?.(scope.row, scope.$index)
                                "
                              >
                                {{ action.label }}
                              </div>
                            </template>
                          </el-dropdown-item>
                        </div>
                      </div>
                      <!-- <el-dropdown-item>The Action 1st</el-dropdown-item>
                <el-dropdown-item>The Action 2st</el-dropdown-item>
                <el-dropdown-item>The Action 3st</el-dropdown-item> -->
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </div>
          </template>

          <template
            v-if="item.type === 'text' && Array.isArray(item.buttonGroup)"
          >
            <div class="table-column-btns" >
              <span
                v-for="(action, index) in item.buttonGroup" v-btnPermissionText="item.permissions"
                :key="index" 
                style="margin-left: 10px"
                :style="
                  item.textColor
                    ? item.textColor + ';margin-left: 0'
                    : 'color: #409eff'
                "
              >
                <span
                  v-if="scope.row && item.prop && scope.row[item.prop]"
                  style="cursor: pointer"
                  @click="() => action.click?.(scope.row, scope.$index)"
                  >{{ scope.row[item.prop] }}
                </span>
              </span>
            </div>
          </template>

          <template
            v-else-if="
              item.type === 'action' && typeof item.buttonGroup == 'function'
            "
          >
            <div class="table-column-btns">
              <span
                v-for="(action, index) in item.buttonGroup(scope.row)"
                :key="index"
                style="margin-left: 10px"
              >
                <!-- {{ permissionsData.includes(action.permission ? action.permission : '') }} -->
                <el-button
                  v-bind="action"
                  @click="() => action.click?.(scope.row, scope.$index)"
                >
                  {{ action.label }}
                </el-button>
              </span>
            </div>
          </template>
          <template v-else-if="item.type === 'icon'">
            <Icon
              v-if="scope.row && item.prop && scope.row[item.prop]"
              style="font-size: 20px"
              :name="scope.row[item.prop]"
            />
          </template>
          <template v-else-if="item.type === 'img'">
            <!-- <Image
              :style="'width: 100%; height: 100%; object-fit: contain'"
              :src="formatter(scope.row, item, scope.row[item.prop])"
            /> -->
          </template>
          <template v-else-if="item.type === 'input'">
            <el-input
              v-model="scope.row[item.prop]"
              style="width: 300px"
              @change="() => item?.inputProps?.onChange(scope.row)"
            />
          </template>
          <template v-else-if="item.type === 'switch'">
            <el-switch
              v-model="scope.row[item.prop]"
              :inline-prompt="item.switchProps?.inlinePrompt ?? true"
              :active-text="item.switchProps?.activeText ?? '启用'"
              :inactive-text="item.switchProps?.inactiveText ?? '禁用'"
              v-bind="item.switchProps"
              @click="() => item?.switchProps?.onChange(scope.row)"
            />
          </template>
          <template v-else-if="item.type === 'html'">
            <span v-html="scope.row[item.prop]" />
          </template>
          <template v-else-if="item.type === 'match'">
            <span
              v-if="
                selectMatch(
                  scope.row[item.prop],
                  item.key || '',
                  item.keyName || '',
                  item.optionList
                )
              "
              >{{
                selectMatch(
                  scope.row[item.prop],
                  item.key || '',
                  item.keyName || '',
                  item.optionList
                )
              }}</span
            >
            <span v-else>--</span>
          </template>
          <template
            v-else-if="
              item.type === 'tag' &&
              formatter(scope.row, item, scope.row[item.prop])
            "
          >
            <el-tag
              :type="colorTag(scope.row[item.prop]) || 'info'"
              size="small"
            >
              {{ formatter(scope.row, item, scope.row[item.prop]) }}
            </el-tag>
          </template>
          <template v-else-if="item.type === 'textColor'">
            <span :style="'color:' + TextColor(scope.row.payStatus)">{{
              scope.row[item.prop]
            }}</span>
          </template>
          <template v-else>
            <span v-if="formatter(scope.row, item, scope.row[item.prop])">
              {{ formatter(scope.row, item, scope.row[item.prop]) }}
              {{ item.unit }}
            </span>
            <span
              v-else-if="
                item.type != 'action' &&
                (formatter(scope.row, item, scope.row[item.prop]) == '' ||
                  formatter(scope.row, item, scope.row[item.prop]) == null)
              "
              >--</span
            >
            <span
              v-else-if="
                item.type != 'action' &&
                formatter(scope.row, item, scope.row[item.prop]) == 0
              "
              >0
            </span>
            <el-tag
              v-if="item.type === 'copy'"
              type="primary"
              style="cursor: pointer; margin-left: 10px"
              @click="
                copyText(formatter(scope.row, item, scope.row[item.prop]))
              "
            >
              复制
            </el-tag>
            <el-tag
              v-if="item.type === 'query'"
              type="primary"
              style="cursor: pointer; margin-left: 10px"
              @click="() => item?.queryProps?.onChange(scope.row)"
            >
              查看
            </el-tag>
          </template>
        </el-config-provider>
      </template>
    </el-table-column>
  </client-only>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import type { TableColumn } from '@/types/table';
import { colorTag } from '@/utils/colorTag';
// import stores from '@/composables/store';
// import type { Login } from '@/types/login';
const { item } = defineProps<{
  item: TableColumn;
}>();
const permissionsList = ref<string[]>([]);
const permissionsData = ref<string[]>([]);
// const permissionsSuper = ref<boolean>(false);
// const permissions = ref<Login>({
//   id: 0,
//   username: '',
//   email: undefined,
//   avatar: undefined,
//   sex: '',
//   created_at: '',
//   roles: [],
//   updated_at: '',
//   role_id: 0,
//   super: false,
//   token: '',
// });
// 复制粘贴
const copyText = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage({
      message: '复制成功',
      type: 'success',
      duration: 2000,
    })
  } catch (err) {
    ElMessage({
      message: '复制失败',
      type: 'error',
      duration: 2000,
    });
  }
};
const showOverflowTooltip = computed(() => {
  if (item.type === 'action') {
    return false;
  }

  return item.componentProps?.showOverflowTooltip ?? true;
});
const matchActionStatus = (action: any, row: any) => {
  // 无配置直接通过
  if (!action?.statusName || action.statusName.length === 0) return true;
  if (!action.status) return true;

  // 统一格式化期望值列表（去空格、过滤空串）
  const expectList = String(action.status)
    .split(',')
    .map((s) => s.trim())
    .filter((s) => s !== '');
  const fields: string[] = Array.isArray(action.statusName)
    ? action.statusName
    : [action.statusName];

  // 字段真实值收集（全部转字符串，避免 1 / '1' 不匹配）
  const fieldValues = fields.map((f) => String((row as any)?.[f]));

  // 1) 精确“位置配对”模式：长度一致 -> 按索引逐一匹配
  if (expectList.length === fieldValues.length) {
    const ok = fields.every(
      (field, idx) => fieldValues[idx] === expectList[idx]
    );
    if (!ok && import.meta && import.meta.env && import.meta.env.DEV) {
      // 仅开发模式下输出调试信息
    }
    return ok;
  }

  // 2) 否则回退为“包含”模式（兼容旧用法：多个字段的值都需在 expectList 中）
  const ok = fieldValues.every((val) => expectList.includes(val));
  if (!ok && import.meta && import.meta.env && import.meta.env.DEV) {
    
  }
  return ok;
};
const TextColor = (value: any) => {
  //已下单
  if (value == '1') {
    return '#e3985b';
  }
  //已支付
  if (value == '2') {
    return '#000';
  }
  //已取消
  if (value == '3') {
    return '#999';
  }
};
onMounted(async () => {
  // const hasTrue: boolean = permissions.value.roles.some(
  //   item => item.super === true
  // );
  // const exists = userInfo.some(item => item.super === true);
  // if (exists) {
  //   permissionsSuper.value = true;
  // } else {
  //   permissionsSuper.value = false;
  // }
  // permissionsList.value = permissionsList.value.map(item => item.permis);
});
const selectMatch = (row: any, key: string, keyName: string, value: any) => {
  //console.log(row, key, keyName, value);

  for (let index = 0; index < value.length; index++) {
    let item = value[index];
    if (item[key] == row) {
      return item[keyName];
    }
  }
};
const formatter = (
  row: any,
  column: TableColumn,
  cellValue: any,
  index?: number
) => {
  if (
    item.componentProps?.formatter &&
    typeof item.componentProps?.formatter === 'function'
  ) {
    return item.componentProps?.formatter(
      row,
      column as any,
      cellValue,
      index as any
    );
  }

  if (item.type === 'datetime' && column.prop && row[column.prop]) {
    return dayjs(row[column.prop]).format('YYYY-MM-DD HH:mm:ss');
  }
  if (item.type === 'date' && column.prop && row[column.prop]) {
    return dayjs(row[column.prop]).format('YYYY-MM-DD');
  }
  if (column.prop) {
    return row[column.prop];
  }
};
</script>
<style>
/* 全局样式文件 */
.el-tooltip__popper {
  min-width: 100px !important;
  max-width: 300px !important;
  white-space: nowrap !important;
}
</style>
<style scoped lang="scss">
.table-column-btns {
  white-space: nowrap;
  display: flex;
}
::v-deep(.el-button--small) {
  padding: 0 !important;
  font-size: 13px !important;
}
.line {
  width: 1px;
  height: 7px;
  background: #e7e7e7;
  border-radius: 0px 0px 0px 0px;
  margin-left: 5px;
}
</style>
